package com.serverdemo.core.net;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * 消息编码
 * Created by wangqiang on 2020/4/9.
 */
public class Encoder extends MessageToByteEncoder<NetPacket>
{
    protected void encode(ChannelHandlerContext channelHandlerContext, NetPacket netPacket, ByteBuf byteBuf) throws Exception
    {
        if (netPacket == null)
        {
            throw new IllegalStateException("netpacket null");
        }

        int netPacketId = netPacket.getId();
        byte[] body = netPacket.getBody();
        int netPacketLength = body.length;

        byteBuf.writeInt(netPacketId);
        byteBuf.writeInt(netPacketLength);
        byteBuf.writeBytes(body);
    }
}
